/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
        {
			name: 'step_filter',
			title: 'step过滤',
			type: 'LineEdit'
		},
        {
			name : 'pth_compensation',
			title : 'PTH补偿',
			type : 'ComboBox',
			property : {
                item_list:[
                    'less_75um',
                    '75_and_100um',
                    '100_and_150um',
                    '150_and_200um',
				],
                tool_tip : 'PTH补偿'
            },
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-04-28 Carver
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 钻孔补偿 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("=============================>JTG_DRL_compensation_aim");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {

    var par = PAR;
	var default_par = {
		step_filter:'unit.+',
		step2:"unit",
        pth_compensation:'100_and_150um',
        auto_save: "No",
        units: 'mm',
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
    }
    
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	// 检查料号是否存在
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	// 检查料号是否被打开
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
	// 检查料号是否能够check out
	if(mode=="aimdfm"){
		if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
		GEN.checkInout({job:job,mode:"out"});
	}
    
    var matrix = GEN.getMatrix({job:job})

    var DrillLayer = Object.keys(matrix).reduce(function(a,b){
        if(matrix[b].context == "board" && matrix[b].layer_type == 'drill'){
            a.push(b)
        }
        return a;
    },[])

    var stepList = GEN.getStepList({job:job})
	// step过滤
    var stepListFilter = stepList.filter(function(step){
		var regexp = new RegExp(par.step_filter,"ig")
		return regexp.test(step)
	})
	if (stepListFilter.length == 0 && par.step2) {
		stepListFilter = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	if(stepListFilter.length == 0) { throw "未发现step:"+par.step_filter }
	stepListFilter.forEach(function(step){
        GEN.openStep({job:job, name:step})
        guard({job:job, step:step})

        //料号初始化
		GEN.clearLayers();  //清除层显示
		GEN.affectedLayer({ mode: 'all', affected: 'no' });  //设置影响层全部不影响
		//操作模式初始化
		GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
		GEN.units({ type: par.units });  //单位初始化
        GEN.zoomHome();  //窗口显示回到原始位置

        // 此处只有一个dril，但是还是要做成循环，这样更通用
        DrillLayer.forEach(function(drill){
           // 
           	GEN.workLayer({name:drill,display_number:2,clear_before:'yes'})
            var feats = GEN.getFeatures({job:job,step:step,layer:drill,options:"feat_index", units:"mm"})
            var drl_feats = []   // 重复的需要删除的孔
            feats.reduce(function(a,b){
                var id = {};
                for(var key in b){
                    var info = b[key]
                    if ( key != "index" && key != "attributes" ) {
                        id[key] = info
                    }
                }
                id = JSON.stringify(id)
                if (a.indexOf(id) < 0) {
                    a.push(id)
                } else {
                    drl_feats.push(b)
                }
                return a
            } , [])
            drl_feats.forEach(function(item){
                GEN.selLayerFeat({layer:drill, index:item.index,operation:"select"})
                if(GEN.getSelectCount() > 0){GEN.selDelete()}
			})
			
			var tmp_chk = "tmp_chk"
			if(GEN.isChklistExists({job:job,step:step,chklist:tmp_chk})){
				GEN.COM("chklist_delete,chklist=" + tmp_chk)
			}

			GEN.COM("chklist_single,action=valor_analysis_drill,show=yes")
			GEN.COM("chklist_pclear")
			GEN.COM("chklist_cupd,chklist=valor_analysis_drill,nact=1,params=((pp_drill_layer="+drill+")(pp_rout_distance=5080)(pp_tests=Hole Separation)(pp_extra_hole_type=Pth\;Npth\;Via)(pp_use_compensated_rout=Skeleton)),mode=regular")
			GEN.COM("chklist_pcopy,chklist=valor_analysis_drill,nact=1")
			GEN.COM("chklist_create,chklist="+tmp_chk)
			GEN.COM("chklist_show,chklist="+tmp_chk)
			GEN.COM("chklist_ppaste,chklist="+tmp_chk+",row=0")
			GEN.COM("chklist_close,chklist=valor_analysis_drill,mode=hide")
			GEN.COM("chklist_cupd,chklist="+tmp_chk+",nact=1,params=((pp_drill_layer="+drill+")(pp_rout_distance=5080)(pp_tests=Hole Separation)(pp_extra_hole_type=Pth\;Npth\;Via)(pp_use_compensated_rout=Skeleton)),mode=regular")
			GEN.COM("chklist_run,chklist="+tmp_chk+",nact=1,area=profile")
			GEN.COM("chklist_create_lyrs,chklist="+tmp_chk+",severity=0")
			GEN.COM("chklist_close,chklist="+tmp_chk+",mode=hide")

			GEN.selRefFeat({layers:"ms_1_" + drill, use:"filter", mode:"touch"})
			if(GEN.getSelectCount() > 0) {
				GEN.PAUSE("check duplicate holes")
			}

			GEN.deleteLayer({job:job, layer:["ms_1_" + drill,"mk_1_" + drill]})
			// 高亮重复孔
			// var queue = []
			// feats.forEach(function(item) {
			// 	if (item.type == "pad") {
			// 		GEN.COM("sel_net_feat,operation=select,x="+item.x+",y="+item.y+",use_ffilter=no")
			// 	} else if (item.type == "line"){
			// 		GEN.COM("sel_net_feat,operation=select,x="+item.xs+",y="+item.ys+",use_ffilter=no")
			// 	}
			// 	if(GEN.getSelectCount() > 1) {
			// 		// 重复
			// 		queue.push(item)
			// 	}
			// 	GEN.selClearFeature()
			// })
			// if(queue.length > 0) {
			// 	queue.forEach(function(item) {
			// 		if (item.type == "pad") {
			// 			GEN.COM("sel_net_feat,operation=select,x="+item.x+",y="+item.y+",use_ffilter=no")
			// 			// GEN.COM("cur_atr_reset")
			// 			// GEN.COM("cur_atr_set,attribute=.string,text=highlight")
			// 			// GEN.COM("sel_change_atr,mode=add")
			// 		} else if (item.type == "line"){
			// 			GEN.COM("sel_net_feat,operation=select,x="+item.xs+",y="+item.ys+",use_ffilter=no")
			// 			// GEN.COM("cur_atr_reset")
			// 			// GEN.COM("cur_atr_set,attribute=.string,text=highlight")
			// 			// GEN.COM("sel_change_atr,mode=add")
			// 		}
			// 	})
			// }

			// GEN.highlightByFilter({attribute:[{attribute:".string", option:"highlight"}]})
			// GEN.selectByFilter({attribute:[{attribute:".string", option:"highlight"}]})
			// if(GEN.getSelectCount() > 0) {
			// 	GEN.COM("sel_delete_atr,attributes=.string")
			// }
			// if(GEN.getSelectCount() > 0) {
			// 	GEN.PAUSE("pause")
			// }
        })

        // GEN.closeStep();
    })


	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}	
} catch (e) {
    IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}


function guard(props) {
    var step = props.step;
    var job = props.job;
    var toolinfo = GEN.getTool({job:job,step:step, layer:"drl"})
    var hasSlot = false;
    for (var key in toolinfo) {
        var info = toolinfo[key]
        if(info.shape == "slot") {
            hasSlot = true
        }
    }
    if(!hasSlot) {
		GEN.workLayer({name:'drl',display_number:2,clear_before:'yes'})
		GEN.selClearFeature()
        GEN.selectByFilter({feat_types:"line"})
        if(GEN.getSelectCount()>0) {
            GEN.selClearFeature()
            IKM.msg("请手动将钻孔管理器改成slot by length模式")
            GEN.PAUSE("pause")
        }
    }
    
}